"""赠品功能"""


from odoo import models, api, fields
from odoo.tools import float_compare
from odoo.exceptions import UserError, ValidationError


class Categ(models.Model):
    _inherit = 'product.category'

    @api.model
    def default_get(self, fields):
        """将产品的开票策略一律改成交货/收到数量"""
        res = super().default_get(fields)
        res['nd_sale_gift_credit_account_id'] = self._get_default_gift_account_id('sale_credit').id
        res['nd_sale_gift_debit_account_id'] = self._get_default_gift_account_id('sale_debit').id
        res['property_cost_method'] = 'fifo'
        res['property_valuation'] = 'real_time'
        return res

    def _get_default_gift_account_id(self, acc_type):
        """获取默认赠品科目"""
        acc_type_dict = {
            'purchase_credit': '',
            'purchase_debit': '',
            'sale_credit': '1405',
            'sale_debit': '1408',
        }
        acc = self.env['account.account'].search([('code', '=', acc_type_dict.get(acc_type, ''))], limit=1)
        return acc

    @api.multi
    def name_get(self):
        result = []
        for categ in self:
            # name = (categ.nd_code or '') + '(' + categ.name + ')'
            result.append((categ.id, categ.name))
        return result

    nd_code = fields.Char('类别编码')
    nd_purchase_gift_credit_account_id = fields.Many2one('account.account', string="采购赠品贷方科目")
    nd_purchase_gift_debit_account_id = fields.Many2one('account.account', string="采购赠品借方科目")
    nd_sale_gift_credit_account_id = fields.Many2one('account.account', string="销售赠品贷方科目")
    nd_sale_gift_debit_account_id = fields.Many2one('account.account', string="销售赠品借方科目")

    @api.model
    def _nd_get_gift_account(self, sale_purchase_line):
        """获取指定销售、采购明细的产品的的赠品科目，以（借方科目，贷方科目）形式返回"""
        sale_purchase_line.ensure_one()
        product_id = sale_purchase_line.product_id
        if product_id.categ_id:
            if sale_purchase_line._name == 'sale.order.line':
                return (product_id.categ_id.nd_sale_gift_debit_account_id, product_id.categ_id.nd_sale_gift_credit_account_id)
            elif sale_purchase_line._name == 'purchase.order.line':
                return (product_id.categ_id.nd_purchase_gift_debit_account_id, product_id.categ_id.nd_purchase_gift_credit_account_id)
            else:
                raise UserError(f'需要根据销售、采购明细行来获取赠品科目，而不是：{sale_purchase_line._name}')
        else:
            raise UserError(f'产品“{product_id.display_name}”没有分类，不能获取赠品相关科目！')
